import streamlit as st
import requests


API_BASE = "http://127.0.0.1:8001"

st.set_page_config(page_title="智能商品推荐助手", layout="centered")
st.title("🛍️ 智能商品推荐助手")

# ✅ 用户名输入
username = st.text_input("请输入用户名：", "alice")

# ✅ 显示用户历史购买记录
user_history = []
if username:
    try:
        resp = requests.get(f"{API_BASE}/api/users/{username}", timeout=90)
        if resp.status_code == 200:
            user_history = resp.json().get("purchased_items", [])
    except Exception as e:
        st.warning(f"加载用户购买记录失败：{e}")

if user_history:
    st.subheader(f"🛍️ 用户 `{username}` 的历史购买记录：")
    for p in user_history:
        with st.expander(f"{p['name']} - ¥{p['price']}"):
            st.write(f"分类：{p['category']}")
            st.write(f"标签：{', '.join(p['tags'])}")
else:
    st.info("该用户尚未有任何购买记录。")

# ✅ 侧边栏模拟购买
with st.sidebar:
    st.header("💳 购买模拟")
    buy_pid = st.number_input("输入要购买的商品 ID", min_value=1, step=1)
    if st.button("确认购买"):
        try:
            resp = requests.post(
                f"{API_BASE}/api/users/{username}/purchase",
                json={"product_id": buy_pid},
                timeout=90
            )
            if resp.status_code == 200:
                st.success("✅ 购买记录已写入，刷新页面再获取推荐吧！")
            else:
                st.error(f"❌ 购买失败：{resp.json().get('detail')}")
        except Exception as e:
            st.error(f"请求失败：{e}")

# ✅ 获取推荐商品（主界面）
if st.button("获取推荐商品"):
    try:
        res = requests.get(f"{API_BASE}/api/recommend", params={"username": username}, timeout=90)
        if res.status_code == 200:
            products = res.json()
            if products:
                st.success(f"为用户 **{username}** 推荐了 {len(products)} 个商品：")
                for p in products:
                    col1, col2 = st.columns([2, 3], gap="large")
                    with col1:
                        st.subheader(p['name'])
                        st.write(f"类别：{p['category']}")
                        st.write(f"价格：¥{p['price']}")
                        if 'tags' in p:
                            st.write(f"标签：{', '.join(p['tags'])}")
                    with col2:
                        st.markdown("##### 🤖 推荐理由")
                        st.write(p.get("reason", "— No reason returned —"))
                    st.markdown("---")
            else:
                st.warning("未能推荐商品，请检查用户名或用户行为数据。")
        else:
            st.error(f"❌ API 请求失败，状态码：{res.status_code}")
    except Exception as e:
        st.error(f"请求异常：{str(e)}")
